var EventProxy = require('eventproxy');
var WechatAPI = require('wechat-api');
var Order = require('../proxy').Order;
var FactionMember = require('../proxy').FactionMember;
var dateUtil = require('../utils/DateUtil');
var logger = require('../service/Logger');
var WechatPay = require('../lib/WechatPay');
var config = require('../config').config;
var needle = require('needle')
var dateUtil = require('../utils/DateUtil');

/**
 * 打赏支付参数装备
 * @param req
 * @param res
 * @param next
 */
exports.payOrder = function(req, res, next){
    var currUser = req.params.currentUser;
    var id = req.params.id;
    var authCode = req.query.code;
    console.log(authCode)
    var order = {
        tradeNo: 'No'+id+'_'+new Date().getTime()
    }
    order.id = id;
    order.goodsName = id+'大洋赏钱'; // 根据商品id不同变化
    order.totalFee = 1; // 根据商品id不同变化
    var pay_param = _buildPayParams(currUser, order);
    console.log(pay_param)
    WechatPay.requestPackage(pay_param, function(err, pkage){
        console.log(pkage)
        if(err) return res.render('others/error', {error: err.msg});
        var jsapi_params = null;
        if(pkage.return_code === 'SUCCESS'){
            jsapi_params = WechatPay.requestJsPay(pkage.prepay_id);
        }
        if(pkage.return_code === 'FAIL'){
            return res.send(pkage.return_msg)
        }
        console.log(jsapi_params)
        res.send({
            jsapi_params: jsapi_params,
            order: order
        });
    });
}
/**
 * 打赏土豪列表
 * @param req
 * @param res
 */
exports.listTuHao = function(req, res){
    var currUser = req.params.currentUser;
    var payId = req.params.payId
    var factionId = '5410286a7c99781e517c7d65'//req.params.factionId;
    Order.findByFactionAndStatus(factionId, 'pay', function(err, orders){
        orders.sort(function(a, b){
            return a.totalFee - b.totalFee
        })
        if(err) return res.render('others/error', {error: err});
        res.render('dashang/dashang_list',
            {   orders: orders,
                factionId: factionId,
                resultMsg: _getResultMsg(payId)});
    });
}
function _getResultMsg(id){
    if(id == 22) return '万水千山总是情，再来一杯行不行~\(≧▽≦)/~'
    if(id == 222) return '为何我的眼中总饱含泪水？因为我装得深沉(╯_╰)'
    if(id == 2222) return '我只想静静编好程序，别问我静静是谁(+﹏+)~'
    if(id == 22222) return '我很好，你也保重╮(╯▽╰)╭'
    return '画面太美我不敢看(╯3╰)……你这么萌你家里人造吗？'
}
function _getRandomRemark(){
    var min = 1, max = 5;
    var index = Math.floor(min+Math.random()*(max-min));
    var str = '接受跪舔中~'
    switch (index){
        case 1:
            str = '如再生父母啊，跪拜~';
            break;
        case 2:
            str = '过年回家的火车票有着落了!';
            break;
        case 3:
            str = '这辈子没见过这么多钱，哭了...';
            break;
        case 4:
            str = '终于能吃上辣条任性一次了，哈哈！';
            break;
        case 5:
            str = '简直是大土豪啊，我们做朋友吧！';
            break;
    }
    return str
}
exports.createOrder = function(req, res){
    var currUser = req.params.currentUser;
    var factionId = req.body.factionId;
    var tradeNo = req.body.tradeNo || 'No_'+new Date().getTime();
    var totalFee = req.body.totalFee;
    var goodsId = req.body.goodsId;
    var goodsName = req.body.goodsName;
    var address = req.body.address;
    console.log({
        factionId: factionId,
        creatorId: currUser.id,
        tradeNo: tradeNo,
        totalFee: totalFee,
        address: address,
        goods: [{
            goodsId: goodsId,
            goodsName: goodsName
        }]
    })
    Order.newAndSave({
        factionId: factionId,
        creatorId: currUser.id,
        tradeNo: tradeNo,
        totalFee: totalFee,
        address: address,
        goods: [{
            goodsId: goodsId,
            goodsName: goodsName
        }]
    }, function(err, order){
        if(err) return res.send({error: err});
        res.send({order: order})
    })
}

exports.myOrder = function(req, res){
    var currUser = req.params.currentUser;
    var status = req.params.status;
    Order.findOrderByUserAndStatus(currUser.id, status, function(err, orders){
        if(err) return res.render('others/error', {error: err});
        res.render('order/myOrder', {orders: orders, status: status, dateUtil: dateUtil});
    })
}

exports.setOrderStatus = function(req, res){
    var currUser = req.params.currentUser;
    var ids = req.body.ids,
        status = req.body.status;
    var ep = new EventProxy();
    ep.after('setStatus', ids.length, function(resps){
        res.send({data: resps});
    })
    ep.bind('error', function(err){
        ep.unbind();
        res.send({error: err});
    });
    ids.forEach(function(id){
        _setStatus(status, id, ep);
    });
}

exports.cancelOrder = function(req, res){
    var currUser = req.params.currentUser;
    var id = req.body.id;
    Order.removeOrder(id, function(req, resp){
        res.send({data: resp})
    })
}

exports.payCurrentOrder = function(req, res){
    var currUser = req.params.currentUser;
    var factionId = req.body.factionId;
    var orderId = req.body.id;
    var address = req.body.address;
    Order.findById(orderId, function(err, order){
        FactionMember.addScore(factionId, currUser.id, parseInt('-'+order.totalFee), function(err, score){
            if(score >= 0){
                //TODO: 保存地址
                Order.addAddress(orderId, address, function(err, resp){
                    
                })
                Order.setPay(orderId, function(err, resp){
                    res.send({data: resp});
                })
            }else{
                res.send({error: '积分余额不足'})
            }
        })
    })
}

function _setStatus(status, id, ep){
    if(status === 'waiting'){
        Order.setWaiting(id, function(err, resp){
            if(err) return ep.emit('error', err);
            ep.emit('setStatus', resp);
        });
    }else if(status === 'pay'){
        Order.setPay(id, function(err, resp){
            if(err) return ep.emit('error', err);
            ep.emit('setStatus', resp);
        });
    }else if(status === 'finish'){
        Order.setFinish(id, function(err, resp){
            if(err) return ep.emit('error', err);
            ep.emit('setStatus', resp);
        });
    }
}

exports.orderlist = function(req, res){
    var currUser = req.params.currentUser;
    var factionId = req.params.factionId;
    var status = req.params.status;
    Order.findByFactionAndStatus(factionId, status, function(err, orders){
        console.log(orders)
        if(err) return res.render('others/error', {error: err});
        res.render('order/order_list',
            {orders: orders, factionId: factionId, status: status, dateUtil: dateUtil});
    });
}

exports.showOrder = function(req, res){
    var currUser = req.params.currentUser;
    var id = req.params.id;
    var authCode = req.query.code;
    Order.findById(id, function(err, order){
        FactionMember.getFmByUserAndFactionId(currUser.id, order.faction, function(err, fm){
            res.render('order/order',
                {order: order,
                    factionId: order.faction,
                    dateUtil: dateUtil,
                    authCode: authCode,
                    factionMember: fm});
        })
    });


}

function _buildPayParams(user, order){
    return {
        openid: user.openid,
        body: order.tradeNo,//TODO:
        out_trade_no: order.tradeNo,
        total_fee: '1', //order.totalFee,//TODO:
        notify_url: config.wechat_url + WechatPay.getNotifyUrl(),
        nonce_str: WechatPay.getNonceStr(32)
    }
}

exports.getWechatAddress = function(req, res, next){
    var authCode = req.body.code;
    console.log(authCode)
    var url = req.headers.referer;
    WechatAPI.requestOAuthAccessToken(authCode, function(err, data){
        var params = WechatPay.requestJsAddr(data.access_token, url);
        console.log(params)
        res.send({params: params})
    })
}

exports.payNotify = function(req, res, next){
    WechatPay.handleNotify(req, res, function(err, msg){
        console.log(msg);
        if(msg.return_code === 'SUCCESS'){
            Order.updateOrderStatus(msg.out_trade_no, {
                status: 'pay',
                wxpayResult: msg,
                remark: _getRandomRemark()
            }, function(err, resp){
                res.send(WechatPay.getNotifyResponseXml('SUCCESS',''));
            })
        }
    })
}
/**
 { return_code: 'SUCCESS',
  appid: 'wxa53d68910d74e151',
  mch_id: '10031711',
  nonce_str: 'f0iq3R0eT4OTDqSfq5nUmlh7cPkmShhg',
  sign: 'AF4B750F8C31F1D0005F74A8431B8C40',
  openid: 'oWvNpuP0jhcQvpOYi_Tq-dBExa74',
  is_subscribe: 'Y',
  trade_type: 'JSAPI',
  bank_type: 'CITIC_CREDIT',
  total_fee: '1',
  fee_type: 'CNY',
  transaction_id: '1002150607201412110006991914',
  out_trade_no: 'No2_1418293011954',
  time_end: '20141211181707' }
 */